package com.example.bbcook;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import db.Ingrediente;
import db.IngredientiDataSource;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ImageListAdapter extends BaseAdapter{
	private Context mContext;

	private LayoutInflater mLayoutInflater;  
	
	IngredientiDataSource datasource;

	private List<Ingrediente> mIngrediente;          

	public ImageListAdapter(Context context) {  
		mContext = context;

		datasource = new IngredientiDataSource(mContext);
		datasource.open();

		datasource.createIngrediente("BROCCOLI", "http://www.worldcommunitycookbook.org/season/guide/photos/broccoli.jpg", "verdura");
		datasource.createIngrediente("POMODORI PACHINO", "http://static.leonardo.it/wp-content/uploads/sites/13/2012/10/pomodoro-di-pachino.jpg", "verdura");
		datasource.createIngrediente("FILETTO PESCE SPADA", "http://www.frigo-star.it/uploads/model_2/img_schede/grandi/tranci_di_spada.jpg", "pesce");
		datasource.createIngrediente("FARINA DI CECI", "http://www.dolci.it/sites/dolci.it/files/2013/farina-ceci.jpg", "farina");
		datasource.createIngrediente("INDIVIA BELGA", "http://www.my-personaltrainer.it/alimentazione/images/indivia-belga.jpg", "verdura");
		mIngrediente = datasource.getAllIngredienti();
		mLayoutInflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return mIngrediente.size();
	}

	@Override
	public Object getItem(int position) {
		return mIngrediente.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView,
			ViewGroup parent) {                                           
		final RelativeLayout itemView;
		if (convertView == null) {                                       
			itemView = (RelativeLayout) mLayoutInflater.inflate(
					R.layout.ingrediente_layout, parent, false);

		} else {
			itemView = (RelativeLayout) convertView;
		}

		//ImageView imageView = (ImageView)
				//   itemView.findViewById(R.id.listImage);                        
		TextView titleText = (TextView)
				itemView.findViewById(R.id.listTitle);                        
		TextView descriptionText = (TextView)
				itemView.findViewById(R.id.listDescription);                  

		String imageUrl = mIngrediente.get(position).getImmagine();   

		new AsyncTask<String, Void, Void>() {
			ProgressBar progressBar =(ProgressBar) itemView.findViewById(R.id.progressBar);
			Bitmap bitmap = null;

			protected void onPreExecute() {
				//Activate progressBar
				progressBar.setVisibility(View.VISIBLE);
				progressBar.setIndeterminate(true);
			};

			@Override
			protected Void doInBackground(String... args) {
				String path = args[0];

				//connection html
				URL imageURL = null;

				try {
					imageURL = new URL(path);
				} 

				catch (MalformedURLException e) {
					e.printStackTrace();
				}

				try {
					System.setProperty("http.keepAlive", "false");
					HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();
					conn.setUseCaches(false); 
					conn.setConnectTimeout(30000);
					conn.setDoOutput(true); 
					conn.setDoInput(true); 

					conn.connect();

					InputStream inputStream = conn.getInputStream();
					//Convert to bitmap
					bitmap = BitmapFactory.decodeStream(inputStream);
				}
				catch (IOException e) {

					e.printStackTrace();
				}

				return null;
			}

			protected void onPostExecute(Void result) {
				progressBar.setVisibility(View.GONE);
				ImageView image = (ImageView) itemView.findViewById(R.id.listImage);

				image.setImageBitmap(this.bitmap);
			};
		}.execute(imageUrl);                

		String title = mIngrediente.get(position).getNome();
		titleText.setText(title);
		String description =
				mIngrediente.get(position).getCategoria();
		if (description.trim().length() == 0) {
			description = "Sorry, no description for this image.";
		}
		descriptionText.setText(description);

		return itemView;
	}

	public void upDateEntries(ArrayList<Ingrediente> ingredienti) {
		mIngrediente = ingredienti;
		notifyDataSetChanged();
	}
}
